package co.za.itweb.defenceweb;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.util.ByteArrayBuffer;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;

public class ItWebLiteActivity extends FragmentActivity {

	RefreshTask rt;

	int max;

	ProgressDialog progressDialog;

	private String density;

	private int width;

	private String mainfolder;
	URL url;
	InputStream input;
	File file;
	OutputStream output;
	SAXParserFactory factory;
	SAXParser parser;
	XMLReader xmlreader;
	RSSHandler theRssHandler;

	private InputSource is;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.start);
/*
		int colors[] = { Color.parseColor("#FF4a79bc"),
				Color.parseColor("#FF4a79bc") };
		GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,
				colors);
		this.getWindow().setBackgroundDrawable(grad);
*/
		if (internetConnection()) {

			DisplayMetrics metrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(metrics);

			width = (int) metrics.widthPixels;
			if (width <= 250) {
				mainfolder = "240";

			} else if (width > 250 && width <= 320) {
				mainfolder = "320";

			} else if (width > 320 && width <= 480) {
				mainfolder = "480";

			} else if (width > 480 && width <= 720) {
				mainfolder = "720";
			} else if (width > 720 && width <= 800) {
				mainfolder = "800";
			} else if (width > 800 && width <= 1280) {
				mainfolder = "1280";
			} else {
				mainfolder = "1280";
			}

			rt = new RefreshTask(this);
			if (rt.getStatus() == AsyncTask.Status.PENDING) {
				// My AsyncTask has not started yet
				rt.execute();
			}

			if (rt.getStatus() == AsyncTask.Status.RUNNING) {
				// My AsyncTask is currently doing work in doInBackground()
			}

			if (rt.getStatus() == AsyncTask.Status.FINISHED) {
				// My AsyncTask is done and onPostExecute was called

			}

		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(
					"There is no internet connection.Please connect to the internet and try again.")
					.setCancelable(false)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {

									dialog.cancel();
									finish();
								}

							});
			AlertDialog alert = builder.create();
			alert.show();

		}

	}

	public boolean internetConnection() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();

		return (info != null && info.isConnected());

	}

	public String determineDensity() {
		switch (getResources().getDisplayMetrics().densityDpi) {
		case DisplayMetrics.DENSITY_LOW:
			density = "ldpi";
			break;
		case DisplayMetrics.DENSITY_MEDIUM:
			density = "mdpi";
			break;
		case DisplayMetrics.DENSITY_HIGH:
			density = "hdpi";
			break;
		case DisplayMetrics.DENSITY_XHIGH:
			density = "xdpi";
			break;

		}
		return density;
	}

	static public boolean hasStorage(boolean requireWriteAccess) {

		String state = Environment.getExternalStorageState();
		

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			if (requireWriteAccess) {
				boolean writable = checkFsWritable();
				
				return writable;
			} else {
				return true;
			}
		} else if (!requireWriteAccess
				&& Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			return true;
		}
		return false;
	}

	private static boolean checkFsWritable() {

		String directoryName = Environment.getExternalStorageDirectory()
				.toString() + "/co.za.itweb/defenceweb/";
		File directory = new File(directoryName);
		if (!directory.isDirectory()) {
			if (!directory.mkdirs()) {
				return false;
			}
		}
		return directory.canWrite();
	}

	private class RefreshTask extends AsyncTask<Void, Integer, Void> {
		// private SaundProgressBar m_regularProgressBar;
		RSSFeed feed;

		public RefreshTask(ItWebLiteActivity activity) {

			// m_regularProgressBar = (SaundProgressBar)
			// findViewById(R.id.regularprogressbar);

		}

		protected void onPreExecute() {
		

		}

		@Override
		protected Void doInBackground(Void... params) {
			if (hasStorage(true)) {
				File storagePath = new File(Environment
						.getExternalStorageDirectory().getPath()
						+ "/co.za.itweb.defenceweb");

				storagePath.mkdirs();
				String[] icons = new String[2];
				if (mainfolder == "240") {
					if (determineDensity() == "ldpi") {
						icons[0] = "dw320.jpg";
					} else if (determineDensity() == "mdpi") {
						icons[0] = "dw240.jpg";
					} else if (determineDensity() == "hdpi") {
						icons[0] = "dw160.jpg";
					} else if (determineDensity() == "xdpi") {
						icons[0] = "dw120.jpg";
					}

				} else if (mainfolder == "320") {
					if (determineDensity() == "ldpi") {
						icons[0] = "dw427.jpg";
					} else if (determineDensity() == "mdpi") {
						icons[0] = "dw320.jpg";
					} else if (determineDensity() == "hdpi") {
						icons[0] = "dw213.jpg";
					} else if (determineDensity() == "xdpi") {
						icons[0] = "dw160.jpg";
					}
				} else if (mainfolder == "480") {
					if (determineDensity() == "ldpi") {
						icons[0] = "dw624.jpg";
					} else if (determineDensity() == "mdpi") {
						icons[0] = "dw480.jpg";
					} else if (determineDensity() == "hdpi") {
						icons[0] = "dw320.jpg";
					} else if (determineDensity() == "xdpi") {
						icons[0] = "dw240.jpg";
					}

				} else if (mainfolder == "720") {
					if (determineDensity() == "ldpi") {
						icons[0] = "dw910.jpg";
					} else if (determineDensity() == "mdpi") {
						icons[0] = "dw700.jpg";
					} else if (determineDensity() == "hdpi") {
						icons[0] = "dw480.jpg";
					} else if (determineDensity() == "xdpi") {
						icons[0] = "dw360.jpg";
					}

				} else if (mainfolder == "800") {
					if (determineDensity() == "ldpi") {
						icons[0] = "dw910.jpg";
					} else if (determineDensity() == "mdpi") {
						icons[0] = "dw700.jpg";
					} else if (determineDensity() == "hdpi") {
						icons[0] = "dw480.jpg";
					} else if (determineDensity() == "xdpi") {
						icons[0] = "dw360.jpg";
					}

				} else if (mainfolder == "1280") {
					if (determineDensity() == "ldpi") {
						icons[0] = "dw910.jpg";
					} else if (determineDensity() == "mdpi") {
						icons[0] = "dw700.jpg";
					} else if (determineDensity() == "hdpi") {
						icons[0] = "dw700.jpg";
					} else if (determineDensity() == "xdpi") {
						icons[0] = "dw624.jpg";
					}

				}

				/*
				 * for (int o = 0; o < FirstScreen.feeds.length; o++) {
				 * DownloadFromUrl
				 * (FirstScreen.feeds[o],FirstScreen.feedslocal[o]);
				 * 
				 * }
				 */

				for (int o = 0; o < FirstScreen.feeds.length; o++) {
					feed = getFeed(FirstScreen.feeds[o]);

					if (feed != null) {
						FirstScreen.fList.add(feed);
					
						int x = o * (100 / FirstScreen.feeds.length + 1);
						publishProgress(x);
						if (isCancelled()) {

							FirstScreen.fList.clear();
							// m_regularProgressBar.setProgress(0);
							// m_regularProgressBar.destroyDrawingCache();
							Intent returnIntent = new Intent();
							returnIntent
									.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							setResult(RESULT_CANCELED, returnIntent);
							finish();

							return null;
						}

					}

				}

				icons[1] = "dw.html";
				for (int x = 0; x < icons.length; x++) {
					try {
						url = new URL(
								"http://itweb.mobi/feed/defenceweb/banners/"
										+ icons[x]);

						input = url.openStream();
					
						if (x == 0) {
							file = new File(storagePath, "dw.jpg");
						} else {
							file = new File(storagePath, icons[x].toString());
						}
						// if (file.exists()) {
						// file.delete();
						// }

						output = new FileOutputStream(file);

						byte[] buffer = new byte[100*1024];

						try {
							int bytesRead = 0;
							while ((bytesRead = input.read(buffer, 0,
									buffer.length)) >= 0) {
								output.write(buffer, 0, bytesRead);

							}
						} finally {
							output.close();
						
							buffer = null;
						}

					} catch (Exception ex) {
						publishProgress(1);

					}
				}

			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// this.m_regularProgressBar.setProgress(values[0]);

		}

		@Override
		protected void onPostExecute(Void result) {

			if (FirstScreen.fList.size() > 0) {

				Intent returnIntent = new Intent();

				setResult(RESULT_OK, returnIntent);
				returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				finish();
			} else {
				Intent returnIntent = new Intent();
				returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				setResult(RESULT_CANCELED, returnIntent);
				finish();
			}

		}
	}

	public RSSFeed getFeed(String urlToRssFeed) {
		try {

			URL url = new URL(urlToRssFeed);

			factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);

			parser = factory.newSAXParser();

			xmlreader = parser.getXMLReader();

			theRssHandler = new RSSHandler();

			xmlreader.setContentHandler(theRssHandler);

			is = new InputSource(url.openStream());
			is.setEncoding("UTF-8");
			xmlreader.parse(is);

			return theRssHandler.getFeed();
		} catch (Exception ee) {
			System.out.println(ee.toString());
			return null;
		}
	}

	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_HOME)) {

			if (rt.getStatus() == AsyncTask.Status.RUNNING) {

				// rt.m_regularProgressBar.setProgress(0);
				rt.cancel(true);
			}
			Intent returnIntent = new Intent();
			returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			setResult(RESULT_CANCELED, returnIntent);

			finish();

		}
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {

			if (rt.getStatus() == AsyncTask.Status.RUNNING) {
				

				rt.cancel(true);
			}
			Intent returnIntent = new Intent();
			returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			setResult(RESULT_CANCELED, returnIntent);
			finish();

		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onBackPressed() {
		if (rt.getStatus() == AsyncTask.Status.RUNNING) {
		

			rt.cancel(true);
		}

		Intent returnIntent = new Intent();
		returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		setResult(RESULT_CANCELED, returnIntent);

		finish();
		return;
	}

}